import React, { useEffect, useState } from 'react'
import { Form, Card, Select, Input, Button, Space, Table, Tag } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { useNavigate } from 'react-router-dom'

import {
  reqGetCityOrDistrict,
  reqGetHospitalList,
  reqGetProvince,
} from '@api/hospital/hospitalList'

import {
  IhospitalList,
  IhospitalItem,
  IdictArr,
} from '@api/hospital/hospitalList/model/hospitalListTypes'

// Option组件是从Select上面解构出来的
const { Option } = Select

let flag = false //是否增加筛选条件

export default function HospitalList() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  // 医院列表数据
  const [hospitalList, setHospitalList] = useState<IhospitalList>([])

  // 分页相关的状态
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)

  // 省数据
  const [province, setProvince] = useState<IdictArr>([])
  // 市数据
  const [city, setCity] = useState<IdictArr>([])
  // 区数据
  const [district, setDistrict] = useState<IdictArr>([])
  // 医院类型
  const [hostype, setHostype] = useState<IdictArr>([])

  // 展示加载效果
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    // 组件挂载获取医院列表数据
    getHospitalList(page, pageSize)
    // 获取省数据
    getProvince()
    // 获取医院类型
    gethosType()
  }, [])

  // 发送请求获取医院列表数据的方法
  async function getHospitalList(page: number, pageSize: number) {
    setLoading(true)
    let result
    if (flag) {
      const params = form.getFieldsValue()
      result = await reqGetHospitalList(page, pageSize, params)
    } else {
      result = await reqGetHospitalList(page, pageSize)
    }

    setHospitalList(result.content)
    setTotal(result.totalElements)
    setLoading(false)
  }

  // 获取省数据的函数
  async function getProvince() {
    const result = await reqGetProvince()
    setProvince(result)
  }
  // 获取市
  async function getCity(parentId: string) {
    const result = await reqGetCityOrDistrict(parentId)
    // console.log(result)
    setCity(result)
    // 清空市和区的表单元素
    form.setFieldsValue({ cityCode: '', districtCode: '' })
  }
  // 获取区
  async function getDistrict(parentId: string) {
    const result = await reqGetCityOrDistrict(parentId)
    // console.log(result)
    setDistrict(result)
    // 清空区的表单元素
    form.setFieldsValue({ districtCode: '' })
  }

  // 获取医院类型
  async function gethosType() {
    const result = await reqGetCityOrDistrict('10000')
    setHostype(result)
  }

  // 查询按钮的事件处理函数
  function onFinish() {
    flag = true
    getHospitalList(page, pageSize)
  }

  // 清空按钮事件处理函数
  function onClear() {
    flag = false
    getHospitalList(page, pageSize)
    // 重置表单.刚好表单初始值就是为空.所以此时用重置更简单
    form.resetFields()
  }

  const columns: ColumnsType<IhospitalItem> = [
    {
      title: '序号',

      render: (a, b, index) => index + 1,
      align: 'center',
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      render(_) {
        return <img src={'data:image/png;base64,' + _} alt="" width="80" />
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      dataIndex: 'param',
      render(_) {
        return _.hostypeString
      },
    },
    {
      title: '详细地址',
      dataIndex: 'param',
      render(_) {
        return _.fullAddress
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(_) {
        return _ ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'status',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            onClick={() => {
              navigate('/syt/hospital/hospitalList/show', {
                state: record.id,
              })
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            onClick={() => {
              navigate(`/syt/hospital/hospitalList/schedule/${record.hoscode}`)
            }}
          >
            排班
          </Button>
          <Button type="primary">{_ ? '下线' : '上线'}</Button>
        </Space>
      ),
    },
  ]
  return (
    <Card>
      <Form layout="inline" form={form} onFinish={onFinish}>
        <Form.Item name="provinceCode" style={{ width: 200 }}>
          <Select placeholder="请选择省" onChange={getCity}>
            {province.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode" style={{ width: 200 }}>
          <Select placeholder="请选择市" onChange={getDistrict}>
            {city.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode" style={{ width: 200 }}>
          <Select placeholder="请选择区">
            {district.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="hosname" style={{ width: 200 }}>
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode" style={{ width: 200 }}>
          <Input placeholder="医院编号"></Input>
        </Form.Item>
        <Form.Item name="hostype" style={{ width: 200, marginTop: 20 }}>
          <Select placeholder="医院类型">
            {hostype.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="status" style={{ width: 200, marginTop: 20 }}>
          <Select placeholder="医院状态">
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>
        <Form.Item style={{ width: 200, marginTop: 20 }}>
          <Button
            htmlType="submit"
            icon={<SearchOutlined />}
            type="primary"
            style={{ marginRight: 10 }}
          >
            查询
          </Button>
          <Button onClick={onClear}>清空</Button>
        </Form.Item>
      </Form>
      <Table
        loading={loading}
        columns={columns}
        dataSource={hospitalList}
        style={{ marginTop: 20 }}
        rowKey="id"
        pagination={{
          total,
          current: page,
          pageSize,
          showQuickJumper: true,
          pageSizeOptions: [5, 10, 15],
          showSizeChanger: true,
          showTotal(total) {
            return `总共${total}条`
          },
          onChange(page, pageSize) {
            setPage(page)
            setPageSize(pageSize)
            getHospitalList(page, pageSize)
          },
        }}
      />
    </Card>
  )
}
